import sys
import re

def main():
 songlist = sys.argv[1]
 artistfile = sys.argv[2]
 songfile = sys.argv[3]
 fin = open(songlist,'r')

 lines = fin.readlines()

 songs = []
 artists = {}

 for line in lines:
	cols = line.split('.')
	file = '.'.join(cols[:-1])
	info = file.split('-')
	if len(info) < 2:
		continue
	try:
        	song = titlize(info[-1].replace('_',' ').strip())
		if len(song) < 3 or song.isdigit():
			continue
		artist = titlize(info[-2].replace('_',' ').strip())
		if (properize(artist) in artists):
			artist = properize(artist)
		if (song in artists):
		#flip song and artist
			song, artist = artist, song
		#check if name is first last instead of last, first
		elif (reverse_name(song) in artists):
			song, artist = artist, reverse_name(song)
		elif (reverse_name(artist) in artists):
			artist = reverse_name(artist)
		elif not(artist in artists):
			artists[artist] = []
		#no duplicates!				
		if not(song in artists[artist]):
			artists[artist].append(song)
			songs.append(song + ' - ' + artist)

	except IndexError:
		continue	
 fin.close()
	
 artist_list = sorted(artists.iterkeys())
 artist_out = open(artistfile,'w')

 for artist in artist_list:
	artist_out.write(artist + '\n')
#	print artists[artist]
	for song in sorted(artists[artist]):
		artist_out.write('\t'+ song + '\n')

 artist_out.close()

 song_out = open(songfile,'w')
 
 song_list = sorted(songs) 

 for song in song_list:
	song_out.write(song + "\n")

 song_out.close()

def reverse_name(artist):
		if len(artist.split(',')) < 2:
	 		split_artist = artist.split(' ')
			return split_artist[-1] + ', ' + " ".join(split_artist[:-1]).strip()
		else:
			return artist

def properize(artist):
		if len(artist.split(',')) < 2:
			return artist + ", The";
		else:
			return artist

def repl_func(m):
    return m.group(1) + m.group(2).upper()

def titlize(s):
	return re.sub("(^|\s)(\S)", repl_func, s)

main()
